package cn.sinata.wanglin;

import android.Manifest;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;

import com.facebook.drawee.view.SimpleDraweeView;
import com.xilada.xldutils.activitys.BaseActivity;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.utils.PermissionManager;
import com.xilada.xldutils.utils.SharedPreferencesUtils;
import com.xilada.xldutils.utils.Utils;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.db.dao.UserDao;
import cn.sinata.wanglin.guide.GuideActivity;
import cn.sinata.wanglin.mine.activity.BindPhoneForAuthActivity;
import cn.sinata.wanglin.mine.activity.LoginStyleActivity;
import cn.sinata.wanglin.model.AppBannerInfo;
import cn.sinata.wanglin.model.LoginInfo;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.ResultData;
import cn.sinata.wanglin.net.model.util.ResultDataSubscriber;
import cn.sinata.wanglin.net.model.util.ResultSubscriber;
import cn.sinata.wanglin.utils.BdNaviMapUtil;
import cn.sinata.wanglin.utils.ImageUtil;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

public class LauncherActivity extends BaseActivity {
    @BindView(R.id.image)
    SimpleDraweeView image;//
    AppBannerInfo mAppBannerInfo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_launcher);
        ButterKnife.bind(this);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏
        //统一请求权限
//        PermissionManager.request(this, Manifest.permission.READ_PHONE_STATE,"读取您的手机状态",20);
//        PermissionManager.request(this, Manifest.permission.READ_CONTACTS,"读取您的手机通讯录",21);
//        PermissionManager.request(this, Manifest.permission.ACCESS_FINE_LOCATION,"获取您的位置信息",22);
//        PermissionManager.request(this, Manifest.permission.WRITE_EXTERNAL_STORAGE,"读取您的存储设备",23);
        getBanner();
        new BdNaviMapUtil(LauncherActivity.this);
        boolean hasP = PermissionManager.request(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE
                ,Manifest.permission.READ_PHONE_STATE
                ,Manifest.permission.READ_CONTACTS
                ,Manifest.permission.ACCESS_FINE_LOCATION
                ,Manifest.permission.RECORD_AUDIO
                ,Manifest.permission.CAMERA},"正常使用必需的权限",24);
        if (hasP) {
            next();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (permissions.length <= 0) {
            return;
        }
        SharedPreferencesUtils.save(permissions[0],false);
        next();
    }

    private void next(){

        ResultSubscriber<Long> timerSub = new ResultSubscriber<Long>(this) {

            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }

            @Override
            public void onNext(Long aLong) {
                super.onNext(aLong);
                boolean fristtoapp=SharedPreferencesUtils.getBoolean(Constant.SP_FRIST_TO_APP,true);
                if(fristtoapp){
                  //第一次进APP则进入引导页
                    SharedPreferencesUtils.save(Constant.SP_FRIST_TO_APP,false);
                    ActivityUtil.create(mContext).go(GuideActivity.class).start();
                    finish();
                }else{
                    String url =  SharedPreferencesUtils.getString(Constant.SP_BANNER_URL);
                    if(!TextUtils.isEmpty(url)){
                        ActivityUtil.create(mContext)
                                .go(BannerActivity.class)
                                .start();
                        finish();
                    }else{
                        //
                        String userid= SharedPreferencesUtils.getString(Constant.SP_USERID);
                        if (!TextUtils.isEmpty(userid)){
                            againLoagin();
                        }else {
                            ActivityUtil.create(mContext)
                                    .go(LoginStyleActivity.class)
                                    .start();
                            finish();
                        }
                    }

                }
            }
        };
        Observable.timer(3, TimeUnit.SECONDS).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(timerSub);

    }

    /**
     * 登录
     */
    private void againLoagin() {
        String type= SharedPreferencesUtils.getString(Constant.SP_LOGIN_TYPE);
        if("C".equals(type)){
            String phone=SharedPreferencesUtils.getString(Constant.SP_PHONE);
            String password=SharedPreferencesUtils.getString(Constant.SP_USER_PWD);
            toLogin(phone,password);
        }else{
             String openID =SharedPreferencesUtils.getString(Constant.SP_LOGIN_OPENID);
            String outhType = SharedPreferencesUtils.getString(Constant.SP_LOGIN_OUTHTYPE);
            String headUrl = SharedPreferencesUtils.getString(Constant.SP_LOGIN_HEADURL);
            String nickName =  SharedPreferencesUtils.getString(Constant.SP_LOGIN_NICKNAME);
            String sex = SharedPreferencesUtils.getString(Constant.SP_LOGIN_SEX);
            autoLogin( openID,  outhType, headUrl, nickName, sex);
        }
    }
    public void autoLogin(String openID, String outhType,String headUrl,String nickName,String sex){
        showDialog("自动登录中...");
        HttpManager.authLogin(openID,outhType,headUrl,nickName,sex).subscribe(new ResultDataSubscriber<LoginInfo>(this) {
            @Override
            public void onSuccess(String msg, LoginInfo loginInfo) {
                showToast(msg);
                SharedPreferencesUtils.save(Constant.SP_USERID,loginInfo.getId());
                SharedPreferencesUtils.save(Constant.SP_HOUSING_ID,loginInfo.getHousingID());
                SharedPreferencesUtils.save(Constant.SP_HOUSING_NAME,loginInfo.getHousingName());
                SharedPreferencesUtils.save(Constant.SP_WANGLINID,loginInfo.getAccount());
                SharedPreferencesUtils.save(Constant.SP_IM_ACCOUNT,loginInfo.getAccount());
                SharedPreferencesUtils.save(Constant.SP_IM_PWD,loginInfo.getImPassword());
                SharedPreferencesUtils.save(Constant.SP_HEADURL,loginInfo.getHeadUrl());
                if(TextUtils.isEmpty(loginInfo.getSex())){
                    SharedPreferencesUtils.save(Constant.SP_SEX,"1");
                }else{
                    SharedPreferencesUtils.save(Constant.SP_SEX,loginInfo.getSex());
                }
                if(TextUtils.isEmpty(loginInfo.getIsforeign())||"0".equals(loginInfo.getIsforeign())){
                    SharedPreferencesUtils.save(Constant.SP_FIND_ME,true);
                }else{
                    SharedPreferencesUtils.save(Constant.SP_FIND_ME,false);
                }
                if(TextUtils.isEmpty(loginInfo.getValid())||"0".equals(loginInfo.getValid())){
                    SharedPreferencesUtils.save(Constant.SP_NEED_AUTH,true);
                }else{
                    SharedPreferencesUtils.save(Constant.SP_NEED_AUTH,false);
                }
                String nick = loginInfo.getNickName();
                if(TextUtils.isEmpty(nick)){
                    nick = "网龄用户";
                }
                SharedPreferencesUtils.save(Constant.SP_NICKNAME,nick);
                UserDao.getInstance(mContext).saveUser(loginInfo.getAccount(),nick,loginInfo.getHeadUrl());
                SharedPreferencesUtils.save(Constant.SP_PHONE,loginInfo.getPhone());
                ActivityUtil.create(mContext).go(MainActivity.class)
                        .start();
                finish();

            }

            @Override
            protected void onError(String code, String msg) {
                super.onError(code, msg);
                ActivityUtil.create(mContext).go(LoginStyleActivity.class)
                        .start();
                finish();
            }
        });
    }
    /**
     * 手机登录接口
     * @param phone
     * @param password
     */
    private void toLogin(final String phone, String password) {
        Observable<ResultData<LoginInfo>> observable = HttpManager.login(phone,password);
        observable.subscribeOn(Schedulers.io())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        showDialog("自动登录中...");
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultDataSubscriber<LoginInfo>(LauncherActivity.this) {
                    @Override
                    public void onSuccess(String msg, LoginInfo loginInfo) {
                        showToast(msg);
                        SharedPreferencesUtils.save(Constant.SP_USERID,loginInfo.getId());
                        SharedPreferencesUtils.save(Constant.SP_HOUSING_ID,loginInfo.getHousingID());
                        SharedPreferencesUtils.save(Constant.SP_HOUSING_NAME,loginInfo.getHousingName());
                        SharedPreferencesUtils.save(Constant.SP_PHONE,phone);
                        SharedPreferencesUtils.save(Constant.SP_WANGLINID,loginInfo.getAccount());
                        SharedPreferencesUtils.save(Constant.SP_IM_ACCOUNT,loginInfo.getAccount());
                        SharedPreferencesUtils.save(Constant.SP_IM_PWD,loginInfo.getImPassword());
                        SharedPreferencesUtils.save(Constant.SP_HEADURL,loginInfo.getHeadUrl());
                        if(TextUtils.isEmpty(loginInfo.getSex())){
                            SharedPreferencesUtils.save(Constant.SP_SEX,"1");
                        }else{
                            SharedPreferencesUtils.save(Constant.SP_SEX,loginInfo.getSex());
                        }
                        if(TextUtils.isEmpty(loginInfo.getIsforeign())||"0".equals(loginInfo.getIsforeign())){
                            SharedPreferencesUtils.save(Constant.SP_FIND_ME,true);
                        }else{
                            SharedPreferencesUtils.save(Constant.SP_FIND_ME,false);
                        }
                        if(TextUtils.isEmpty(loginInfo.getValid())||"0".equals(loginInfo.getValid())){
                            SharedPreferencesUtils.save(Constant.SP_NEED_AUTH,true);
                        }else{
                            SharedPreferencesUtils.save(Constant.SP_NEED_AUTH,false);
                        }
                        String nick = loginInfo.getNickName();
                        if(TextUtils.isEmpty(nick)){
                            nick = Constant.DEFULT_NICKNAME;
                        }
                        SharedPreferencesUtils.save(Constant.SP_NICKNAME,nick);
                        UserDao.getInstance(mContext).saveUser(loginInfo.getAccount(),nick,loginInfo.getHeadUrl());
                        ActivityUtil.create(mContext).go(MainActivity.class)
                                .start();
                        finish();
                    }

                    @Override
                    protected void onError(String code, String msg) {
                        super.onError(code, msg);
                        ActivityUtil.create(mContext).go(LoginStyleActivity.class)
                                .start();
                        finish();
                    }
                });
    }
    public void getBanner(){
        HttpManager.getStartPage()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultSubscriber<ResultData<AppBannerInfo>>(this) {
                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        next();
                    }

                    @Override
                    public void onNext(ResultData<AppBannerInfo> resultData) {
                        super.onNext(resultData);
                        if ("SUCCESS".equals(resultData.getCode())){
                             if(resultData.getData()!=null){
                                mAppBannerInfo=resultData.getData();
                                Utils.systemErr("getImgUrl"+resultData.getData().getImgUrl());
                               if(!TextUtils.isEmpty(resultData.getData().getImgUrl())){
                                   SharedPreferencesUtils.save(Constant.SP_BANNER_URL,resultData.getData().getImgUrl());
                                   SharedPreferencesUtils.save(Constant.SP_BANNER_TYPE,resultData.getData().getJumpType());
                                   SharedPreferencesUtils.save(Constant.SP_BANNER_JUMP_URL,resultData.getData().getJumpUrl());
                               }
                            }
                        }
                    }
                });
    }
}
